<?php
/**
 * Created by PhpStorm.
 * User: Raytine
 * Date: 2019/11/21
 * Time: 22:51
 */

namespace App\Service;


use App\Exceptions\ApiException;
use App\Interfaces\MapInterFace;
use GuzzleHttp\Client;

class TengxunMapService implements MapInterFace
{
    protected  $client;
    protected  $url='https://apis.map.qq.com';
    protected   $ak;
    public function __construct(Client $client)
    {
        $this->client=$client;
        $this->ak=config('baiduMap.tengxun_ak');
    }

    public function geocoding($address,$city=''){
        $uri='/ws/geocoder/v1/';
        $query=[
            'address'=>$address,
            'region'=>$city
        ];
        $result= $this->getData($uri,$query);
        return $result;
    }

    /**
     * @param $uri
     * @param $query
     * @return string
     */
    protected function getData($uri,$query){
       $response=$this->client->get($this->url.$uri,[
            'query'=>array_merge(['key'=>$this->ak,'output'=>'json'],$query)
        ]);

        $data=  json_decode($response->getBody()->getContents(),true);
        if ($data['status']==0){
            \Log::channel('baiduMap')->info('调用geocoding成功',$data);
            return [
                $data['result']['location']['lat'],
                $data['result']['location']['lng'],
            ];
        }else{
            \Log::channel('baiduMap')->info('调用geocoding失败',$data);
            throw  new ApiException('地图错误');
        }
    }

}
